package com.neusoft.databus.policy.applicationEvent.listener;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import com.google.common.eventbus.AsyncEventBus;
import com.neusoft.databus.policy.applicationEvent.PolicyBindEvent;
import com.neusoft.databus.policy.applicationEvent.PolicyDeleteEvent;
import com.neusoft.databus.policy.enums.EventStatus;
import com.neusoft.databus.policy.model.Event;
import com.neusoft.databus.policy.model.Policy;
import com.neusoft.databus.policy.service.EventService;

import lombok.extern.slf4j.Slf4j;

/**
 * 策略事件处理类
 *
 * @author naxiang
 */
@Slf4j
@Component
public class PolicyApplicationEventListener implements ApplicationListener<ApplicationEvent> {
    @Autowired
    private EventService eventService;
    @Autowired
    private AsyncEventBus policyEventBus;

    @Override
    public void onApplicationEvent(final ApplicationEvent event) {
        if (event instanceof PolicyDeleteEvent) {
            final PolicyDeleteEvent policyDeleteEvent = (PolicyDeleteEvent) event;
            final Policy policy = policyDeleteEvent.getPolicy();
            PolicyApplicationEventListener.log.info("策略禁用触发告警解除事件！{}", policy.getCode());
            final List<Event> alarmEvents =
                    this.eventService.findByPolicyIdAndStatus(policy.getId(),
                            EventStatus.UNFIXED);
            alarmEvents.forEach(e -> {
                e.setStatus(EventStatus.FIXED);
                e.setPolicy(policy);
                this.policyEventBus.post(e);
            });
        } else if (event instanceof PolicyBindEvent) {
            final PolicyBindEvent policyBindEvent = (PolicyBindEvent) event;
            PolicyApplicationEventListener.log.info("策略绑定资源触发告警解除事件！{}",
                    policyBindEvent.getResourceCodeList().toString());
            policyBindEvent.getResourceCodeList().forEach(c -> {
                final List<Event> alarmEvents =
                        this.eventService.findByResourceCodeAndStatus(c,
                                EventStatus.UNFIXED);
                alarmEvents.forEach(e -> {
                    e.setStatus(EventStatus.FIXED);
                    this.policyEventBus.post(e);
                });
            });
        }
    }

}
